package com.mm.mweather

import android.content.Intent
import android.content.SharedPreferences
import android.graphics.Color
import android.os.Build
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.preference.PreferenceManager
import android.support.v4.view.GravityCompat
import android.support.v4.widget.DrawerLayout
import android.support.v4.widget.SwipeRefreshLayout
import android.view.LayoutInflater
import android.view.View
import android.widget.*
import com.bumptech.glide.Glide
import com.mm.mweather.gson.Aqi
import com.mm.mweather.gson.Suggestion
import com.mm.mweather.gson.Weather
import com.mm.mweather.service.AutoUpdateService
import com.mm.mweather.util.HttpUtil
import com.mm.mweather.util.Utility
import kotlinx.android.synthetic.main.aqi.*
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import java.io.IOException

class MainActivity : AppCompatActivity() {

    var drawerLayout: DrawerLayout?=null

    private var weatherlayout: ScrollView? = null
    private var titleCity: TextView? = null
    private var titleUpdateTime: TextView? = null
    private var degreeText: TextView? = null
    private var weatherInfoText: TextView? = null
    private var forecastLayout: LinearLayout? = null
    private var apiText: TextView? = null
    private var pm25Text: TextView? = null
    private var comfortText: TextView? = null
    private var carWashText: TextView? = null
    private var sportText: TextView? = null
    private var bingPicImg: ImageView? = null

    private var swipeRefresh: SwipeRefreshLayout?=null

    private var mWeatherId:String? = null



    private var navButton: Button?=null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        drawerLayout = findViewById<DrawerLayout>(R.id.drawer_layout)
        drawerLayout!!.openDrawer(GravityCompat.START)

        //初始化控件
        weatherlayout = findViewById<View>(R.id.weather_layout) as ScrollView
        titleCity = findViewById<View>(R.id.title_city) as TextView
        titleUpdateTime = findViewById<View>(R.id.title_time) as TextView
        degreeText = findViewById<View>(R.id.degree_text) as TextView
        weatherInfoText = findViewById<View>(R.id.weather_info_text) as TextView
        forecastLayout = findViewById<LinearLayout>(R.id.forecast_layout)
        apiText = findViewById<View>(R.id.aqi_text) as TextView
        pm25Text = findViewById<View>(R.id.pm25_text) as TextView
        comfortText = findViewById<View>(R.id.comfort_text) as TextView
        carWashText = findViewById<View>(R.id.car_wash_text) as TextView
        sportText = findViewById<View>(R.id.sport_text) as TextView
        bingPicImg = findViewById<View>(R.id.bing_pic_img) as ImageView




        swipeRefresh = findViewById<SwipeRefreshLayout>(R.id.swipe_refresh)

        swipeRefresh!!.setColorSchemeResources(R.color.colorPrimary)

        swipeRefresh!!.setOnRefreshListener {


            resquestWeather(mWeatherId!!)
        }
        var prefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(this@MainActivity)

        var weatherStr:String?=prefs.getString("weather",null)

        if (weatherStr!=null) {
            var weather: Weather = Utility.handleWeatherResponse(weatherStr)
            runOnUiThread {
                if (weather != null && "ok".equals(weather.status)) {
                    showWeatherInfo(weather)
                }
            }
        }
        var aqistr:String?=prefs.getString("aqi",null)
        if (aqistr!=null) {
            var aqi: Aqi = Utility.handleAqiResponse(aqistr)
            runOnUiThread {
                if (aqi != null && "ok".equals(aqi.status)) {
                    showAqiInfo(aqi)
                }
            }
        }


        var bingPic: String? = prefs.getString("bing_pic", null)
        if (bingPic !== null) {

            Glide.with(this@MainActivity).load(bingPic).into(bingPicImg)
        } else {
            loadBingPic()
        }


        navButton = findViewById<Button>(R.id.nav_button)

        navButton!!.setOnClickListener { v ->

            drawerLayout!!.openDrawer(GravityCompat.START)
        }

    }


    fun resquestWeather(weatherId:String){
        mWeatherId=weatherId
        var address:String="https://free-api.heweather.net/s6/weather?location="+weatherId+"&key=f9aeb541625441499a2b8d89aba9e08c"
        HttpUtil.sendOkHttpRequests(address, object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                runOnUiThread {
                    Toast.makeText(this@MainActivity, "获取天气信息失败", Toast.LENGTH_SHORT).show()
                    swipeRefresh!!.isRefreshing = false
                }
            }


            override fun onResponse(call: Call, response: Response) {
                val resposeText = response.body()!!.string()
                val weather: Weather = Utility.handleWeatherResponse(resposeText)
                runOnUiThread {
                    if (weather!=null&&"ok".equals(weather.status)){
                        var editor:SharedPreferences.Editor=PreferenceManager.getDefaultSharedPreferences(this@MainActivity).edit()
                        editor.putString("weather",resposeText)
                        editor.apply()
                        showWeatherInfo(weather)
                    }
                    swipeRefresh!!.isRefreshing = false
                }
            }
        })
    }


    fun resquestapi(weatherId:String){
        mWeatherId=weatherId
        var address:String="https://free-api.heweather.net/s6/air/now?location="+weatherId+"&key=f9aeb541625441499a2b8d89aba9e08c"
        HttpUtil.sendOkHttpRequests(address, object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                runOnUiThread {
                    Toast.makeText(this@MainActivity, "获取空气质量信息失败", Toast.LENGTH_SHORT).show()
                    swipeRefresh!!.isRefreshing = false
                }
            }


            override fun onResponse(call: Call, response: Response) {
                val resposeText = response.body()!!.string()
                val aqi: Aqi = Utility.handleAqiResponse(resposeText)
                runOnUiThread {
                    if (aqi!=null&&"ok".equals(aqi.status)){
                        var editor:SharedPreferences.Editor=PreferenceManager.getDefaultSharedPreferences(this@MainActivity).edit()
                        editor.putString("aqi",resposeText)
                        editor.apply()
                        showAqiInfo(aqi)
                    }
                    swipeRefresh!!.isRefreshing = false
                }
            }
        })
    }

    fun showWeatherInfo( weather: Weather){
        var cityName:String?= weather.basic!!.cityName
        var updateTime:String?=weather.update!!.loc
        var degree:String? = weather.now!!.tempterature + "℃"
        var weatherInfo:String? = weather.now!!.info

        titleCity!!.text = cityName
        titleUpdateTime!!.text = updateTime
        degreeText!!.text = degree
        weatherInfoText!!.text = weatherInfo

        forecastLayout!!.removeAllViews()

        for (forecast in weather.forecastList!!){
            var view:View= LayoutInflater.from(this).inflate(R.layout.forecast_item,forecastLayout,false)
            var dateText:TextView = view.findViewById<View>(R.id.date_text) as TextView
            var infoText:TextView = view.findViewById<View>(R.id.info_text) as TextView
            var maxText:TextView = view.findViewById<View>(R.id.max_text) as TextView
            var minText:TextView = view.findViewById<TextView>(R.id.min_text)

            dateText.text=forecast.date
            infoText.text=forecast.info
            maxText.text=forecast.tempterature_max
            minText.text=forecast.tempterature_min
            forecastLayout!!.addView(view)


        }
        var comfSuggestion: Suggestion = weather.suggestionList!!.findLast { o->o.type=="comf" }!!

        comfortText!!.text="舒适度："+comfSuggestion.brf+","+comfSuggestion.txt

        var cwSuggestion: Suggestion = weather.suggestionList!!.findLast { o->o.type=="cw" }!!
        carWashText!!.text="洗车指数："+cwSuggestion.brf+","+cwSuggestion.txt

        var sportuggestion: Suggestion = weather.suggestionList!!.findLast { o->o.type=="sport" }!!
        sportText!!.text="运动建议："+sportuggestion.brf+","+sportuggestion.txt



    }
    fun showAqiInfo(aqi: Aqi){

        var aqis:String?=aqi.aqiInfo!!.aqi
        var pm25:String?= aqi.aqiInfo!!.pm25

        aqi_text.text=aqis
        pm25_text.text=pm25

        weatherlayout!!.visibility=View.VISIBLE

    }

    fun loadBingPic(){
        val picUrl:String = "http://guolin.tech/api/bing_pic";
        HttpUtil.sendOkHttpRequests(picUrl,object : Callback {

            override fun onFailure(call: Call?, e: IOException?) {
                e!!.printStackTrace()
            }


            override fun onResponse(call: Call?, response: Response) {
                val bingPic:String=response.body()!!.string()

                var editor:SharedPreferences.Editor=PreferenceManager.getDefaultSharedPreferences(this@MainActivity).edit()
                editor.putString("bing_pic",bingPic)
                editor.apply()
                runOnUiThread{
                    Glide.with(this@MainActivity).load(bingPic).into(bingPicImg)

                }
            }
        })
    }
}
